package com.hainiu.cat.sort.write;

import com.hainiu.cat.util.SortUtil;

/**
 * create by biji.zhao on 2021/5/30
 *
 * 二分查找法
 */
public class BinarySearch {

    public static void main(String[] args) {
        int [] assays = {1, 2, 3, 5, 7, 30, 47, 58, 100};
        SortUtil.arrayToString(assays);
        System.out.println(searching(assays, 0, assays.length - 1, 2));
        System.out.println(searching(assays, 0, assays.length - 1, 10));
        System.out.println(searching(assays, 0, assays.length - 1, 100));
    }

    private static int searching(int [] array, int begin, int end, int key) {
        int mid = (end - begin) / 2 + begin;
        if (array[mid] == key) {
            return mid;
        }
        if (begin >= end) {
            return -1;
        }
        if (array[mid] > key) {
            return searching(array, begin, mid - 1, key);
        }
        return searching(array, mid + 1, end, key);
    }


}
